<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/19 13:38
 * Desc:
 */
class Service_Api_Integral_Mall extends Contract_Api_Integral_Mall
{

    public function attr(): array
    {
        return DB::select('id', DB::expr('attrname as attr_name'))
            ->from('integral_attr')
            ->where('isopen', '=', 1)
            ->and_where('id', '!=', 1)
            ->order_by(DB::expr('IFNULL(`displayorder` ,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    public function query(array $params): array
    {
        /**
         * @var $pagesize
         * @var $page
         * @var $attr_id
         * @var $flag
         */
        extract($params);

        $offset = St_Page::offset($page, $pagesize);

        switch ($flag) {
            case 'attr':
                $list = Model_Api_V2_Integral_Mall::get_integral($offset, $pagesize, $attr_id);
                break;
            case 'order':
                $list = Model_Api_V2_Integral_Mall::get_integral($offset, $pagesize);
                break;
        }

        foreach ($list as $k=>&$item) {
            $item['litpic'] = $this->img_url($item['litpic']);
            if($item['member_max_number']>0 && $item['number']>0 && $params['member_id']){
                $member_max_number = min($item['number'], $item['member_max_number']);
                $book_num = DB::select()->from('member_order')
                    ->where('typeid','=',107)
                    ->and_where('memberid','=',$params['member_id'])
                    ->and_where('productautoid','=',$item['id'])
                    ->execute()->count();
                $item['number'] = $book_num>=$member_max_number?0:$member_max_number;
            }else{
                if($item['member_max_number']>0 && $item['number']>0){
                    $item['number'] = min($item['number'], $item['member_max_number']);
                }
            }
            unset($list[$k]['member_max_number']);
        }

        return $list;
    }

    public function info(int $id, int $mid = 0): array
    {
        //产品id
        $info = Model_Integral::get_integral_info_by_id($id);
        if (!$info) {
            throw new Exception('产品不存在');
        }

        $pic = array();
        foreach ($info['piclist'] as $item) {
            $pic[] = $this->img_url($item[0]);
        }

        $info['litpic']            = $this->img_url($info['litpic']);
        $info['piclist']           = $pic;
        $info['need_jifen']        = intval($info['need_jifen']);//需要的积分
        $info['need_address']      = intval($info['need_address']);//是否需要地址
        $info['number']            = intval($info['number']);//库存
        $info['member_max_number'] = intval($info['member_max_number']);//单个用户最多兑换个数
        $info['content']           = $this->content_add_domain($info['content']);

        //用户已兑换数量
        $get_num = 0;
        if ($mid) {
            $get_num = DB::select(DB::expr('sum(`dingnum`) as num'))
                ->from('member_order')
                ->where('typeid', '=', 107)
                ->and_where('productautoid', '=', $id)
                ->and_where('memberid', '=', $mid)
                ->execute()
                ->get('num');
        }
        $info['get_num'] = intval($get_num);

        unset($info['webid']);
        unset($info['aid']);
        unset($info['displayorder']);
        unset($info['ishidden']);
        unset($info['addtime']);
        unset($info['modtime']);

        return $info;
    }

    public function get_default_address(int $mid): array
    {
        $data = array();

        $addresses = Model_Member_Address::get_address($mid);
        // 默认地址
        $default_address = array();
        // 是否有默认地址
        $has_default = false;
        if (!empty($addresses)) {
            foreach ($addresses as $address) {
                if ($address['is_default'] == 1) {
                    $default_address = $address;
                    $has_default     = true;
                    break;
                }
            }
            $default_address = !$has_default ? $addresses[0] : $default_address;
            //是否有默认值 true：有，false：无
            $data['has_default'] = true;
        } else {
            $data['has_default'] = false;
        }

        if (!empty($default_address)) {
            unset($default_address['memberid']);
        }

        //默认地址数据
        $data['default'] = $default_address;

        return $data;
    }

    public function exchange(int $mid, array $params): array
    {
        /**
         * @var $id
         * @var $book_num //预订数量
         * @var $linkman //联系人姓名
         * @var $linktel //联系人手机号
         * @var $linkemail //联系人邮箱
         * @var $remark //备注
         * @var $receive_address_id //收货地址id
         */
        extract($params);

        //产品信息
        $info = Model_Integral::get_integral_info_by_id($id);
        if (!$info) {
            throw new Exception('产品不存在');
        }

        //用户已兑换数量
        $get_num = DB::select(DB::expr('sum(`dingnum`) as num'))
            ->from('member_order')
            ->where('typeid', '=', Model_Api_V2_Integral_Mall::TYPE_ID)
            ->and_where('productautoid', '=', $id)
            ->and_where('memberid', '=', $mid)
            ->execute()
            ->get('num');
        if ($book_num + $get_num > $info['member_max_number']) {
            //兑换数量+已兑换数量>单个用户最大订购量
            throw new Exception('预订数量超过单个用户最大订购量');
        }

        //判断收货地址
        if ($info['need_address']) {
            if (!$receive_address_id) {
                throw new Exception('请添加收货地址');
            }

            //检查该用户地址是否可用
            if (!Model_Member_Address::check_address_id($mid, $receive_address_id)) {
                throw new Exception('收货地址不可用，请重新选择');
            }
        } else {
            unset($params['receive_address_id']);
        }

        //用户信息
        $member = Model_Member::get_member_byid($mid);
        if ($member['jifen'] < $book_num * $info['need_jifen']) {
            //积分不足
            throw new Exception('积分不足');
        }

        $params['info'] = $info;
        //下订单
        $order_id = Model_Api_V2_Integral_Mall::exchange($mid, $params);

        return array(
            'order_id' => $order_id,
        );
    }

    public function get_order_list(int $mid, array $params = array()): array
    {
        /**
         * @var $page
         * @var $pagesize
         */
        extract($params);

        //查询列表
        $builder = DB::select('id', 'ordersn', 'productname', 'litpic', 'addtime', 'needjifen', 'productaid')
            ->from('member_order')
            ->where('typeid', '=', Model_Api_V2_Integral_Mall::TYPE_ID)
            ->and_where('memberid', '=', $mid)
            ->order_by('addtime', 'desc');

        if (!empty($page) && !empty($pagesize)) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $list = $builder->execute()->as_array();

        $mall_types = array();
        if (!empty($list)) {
            $product_aids = Arr::pluck($list, 'productaid');
            $mall_types   = DB::select()
                ->from('integral')
                ->where('id', 'in', $product_aids)
                ->execute()
                ->as_array('id', 'mall_type_id');
        }

        //产品属性
        $attr_arr = DB::select('id', 'attrname')
            ->from('integral_attr')
            ->execute()
            ->as_array('id', 'attrname');

        foreach ($list as &$l) {
            $mall_type_id  = $mall_types[$l['productaid']] ?? 0;
            $l['litpic']   = $this->img_url($l['litpic']);
            $l['addtime']  = date('Y-m-d H:i:s', $l['addtime']);
            $l['attrname'] = $attr_arr[$mall_type_id] ?? '其他';
        }

        return $list;
    }

    public function get_order_info(int $mid, int $id): array
    {
        //订单id
        $info = Model_Member_Order::get_order_detail($id, $mid);
        if (!$info) {
            throw new Exception('订单不存在');
        }

        $filter_keys = array(
            'litpic', 'productname', 'needjifen', 'dingnum', 'receiver_address_id', 'addtime', 'remark',
            'linkman', 'linktel', 'linkemail', 'type_id',
        );
        $info        = $this->filter_data($filter_keys, $info);

        if ($info['receiver_address_id']) {
            //收货地址信息
            $address = Model_Member_Address::get_address_info($info['receiver_address_id']);
            if ($address) {
                unset($address['memberid']);
                unset($address['is_default']);
                unset($address['id']);
            }
            $info['address_info'] = $address;
        }

        //产品积分单价
        $info['single_jifen'] = bcdiv($info['needjifen'], $info['dingnum']);
        //图片地址
        $info['litpic']  = $this->img_url($info['litpic']);
        $info['addtime'] = date('Y-m-d H:i:s', $info['addtime']);
        //备注
        $info['remark'] = unserialize($info['remark'])['book'];

        return array(
            'info' => $info,
        );
    }
}